package com.liujg.future.util;

import com.alibaba.fastjson.JSON;
import org.apache.logging.log4j.util.Strings;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import java.util.stream.Collectors;

public class SingleHttpClient {

    public static String get(String baseUrl, String path, Map<String,Object> params) throws URISyntaxException, IOException, InterruptedException {


        StringBuilder uri = new StringBuilder(baseUrl);
        uri.append(path);
        if(!params.isEmpty()){
            uri.append("?");
            params.forEach((k,v)-> uri.append(k).append("=").append(v).append("&"));
            uri.deleteCharAt(uri.length()-1);
        }
        // 创建 HttpClient 实例
        HttpClient client = HttpClient.newHttpClient();
        // 创建 HttpRequest 实例
        HttpRequest request = HttpRequest.newBuilder()
                .uri(new URI(uri.toString()))
                .build();

        // 发送同步 HTTP 请求
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        // 检查响应状态码
        if (response.statusCode() == 200) {
            // 获取响应体并转换为 String
            return response.body();
        } else {
            throw new RuntimeException("请求失败，状态码：" + response.statusCode());
        }
    }

    public static String post(String baseUrl, String path, Map<String,Object> params)  {


        String uri = baseUrl + path;
        String requestBody = JSON.toJSONString(params);
        // 创建 HttpClient 实例
        HttpClient client = HttpClient.newHttpClient();
        try {
            // 创建 HttpRequest 实例
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(new URI(uri))
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .header("Content-Type", "application/json") // 设置 Content-Type
                    .build();

            // 发送同步 HTTP 请求
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            // 检查响应状态码
            if (response.statusCode() == 200) {
                // 获取响应体并转换为 String
                return response.body();
            } else {
                throw new RuntimeException("请求失败，状态码：" + response.statusCode());
            }
        }catch (URISyntaxException| IOException| InterruptedException e){
            e.printStackTrace();
            return "{\"code\":-1001}";

        }
    }

    public static String postForm(String baseUrl, String path, Map<String,Object> params) throws Exception {
        String uri = baseUrl + path;

        // 创建 HttpClient 实例
        HttpClient client = HttpClient.newHttpClient();

        // 创建 HttpRequest 实例
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(uri)) // 替换为实际的 API 地址
                .header("Content-Type", "application/x-www-form-urlencoded")
                .POST(HttpRequest.BodyPublishers.ofString(
                        params.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.joining("&")))
                )
                .build();

        // 发送请求并获取响应
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        // 检查响应状态码
        if (response.statusCode() == 200) {
            // 获取响应体并转换为 String
            return response.body();
        } else {
            throw new RuntimeException("请求失败，状态码：" + response.statusCode());
        }
    }


}
